//
//  GrammarManager.m
//  Grammar
//
//  Created by Rick on 7/11/13.
//
//

#import "GrammarManager.h"
#import "Grammar.h"

#define TYGrammar @"TYGrammar"
#define TYGrammarArchiver @"TYGrammarArchiver"

@interface GrammarManager()
-(void)restore;
@end

@implementation GrammarManager
static GrammarManager *_sharedInst = nil;

+(GrammarManager*)sharedManager
{
    @synchronized(self) {
        if (_sharedInst == nil) {
            _sharedInst = [[self alloc] init];
        }
    }
    return _sharedInst;
}

- (id)init
{
    if ((self = [super init])) {
        [self restore];
    }
    return self;
}

- (void)saveData
{
    if (_grammars) {
        NSMutableData *data = [[NSMutableData alloc] init];
        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]
                                     initForWritingWithMutableData:data];
        [archiver encodeObject:_grammars forKey:TYGrammarArchiver];
        [archiver finishEncoding];
        [USER_DEFAULT setObject:data forKey:[NSString stringWithFormat:@"%@%@",TYGrammar,_grammarType] ];
        [archiver release];
        [data release];
        
        [USER_DEFAULT synchronize];
    }
}

- (void)readData{
    NSData *data = [USER_DEFAULT objectForKey:[NSString stringWithFormat:@"%@%@",TYGrammar,_grammarType]];;
    if (!data) {
        return;
    }
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    NSArray *array = [unarchiver decodeObjectForKey:TYGrammarArchiver];
    [unarchiver finishDecoding];
    [_grammars addObjectsFromArray:array];
    [unarchiver release];
}

- (void)addGrammar:(Grammar *)grammar
{
    for (Grammar *aGrammar in self.grammars) {
        if ([aGrammar.grammarId isEqualToString:grammar.grammarId]) {
            return;
        }
    }
    [_grammars insertObject:grammar atIndex:0];
    
    [self saveData];
}

- (void)updateGrammar:(Grammar*)grammar
{
    NSArray *array = [NSArray arrayWithArray:self.grammars];
    for (Grammar *aGrammar in array) {
        if ([aGrammar.grammarId isEqualToString:grammar.grammarId]) {
            [self removeGrammar:aGrammar];
            [_grammars insertObject:grammar atIndex:0];
        }
    }
    
    [self saveData];
}

- (void)removeGrammar:(Grammar *)grammar
{
    NSArray *array = [NSArray arrayWithArray:self.grammars];
    for (Grammar *aGrammar in array) {
        if ([aGrammar.grammarId isEqualToString:grammar.grammarId]) {
            [_grammars removeObject:aGrammar];
            [self saveData];
        }
    }
}

- (NSMutableArray*)grammars
{
    [self clearMemoryData];
    [self readData];
    
    return _grammars;
}

- (void)restore
{
    self.grammars = [NSMutableArray array];
    [self readData];
}

- (void)clearMemoryData
{
    [_grammars removeAllObjects];
}

- (void)removeAllGrammars
{
    [_grammars removeAllObjects];
    [USER_DEFAULT removeObjectForKey:[NSString stringWithFormat:@"%@%@",TYGrammar,_grammarType]];
    [USER_DEFAULT synchronize];
}
@end
